<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <!-- 老人姓名搜索：确保v-model和prop与查询参数一致 -->
            <el-form-item label="老人姓名" prop="elderName">
                <el-input v-model="queryParams.elderName" placeholder="请输入老人姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="床位号" prop="bedNo">
                <el-input v-model="queryParams.bedNo" placeholder="请输入床位号" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>



        <el-table v-loading="loading" :data="balanceList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center">
                <template #default="scope">
                    <span>{{ scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="老人姓名" align="center" prop="elderName" />
            <el-table-column label="床位号" align="center" prop="bedNo" />
            <!-- <el-table-column label="预交款余额" align="center" prop="prepaidBalance" /> -->
            <!-- <el-table-column label="押金金额" align="center" prop="depositAmount" /> -->
            <el-table-column label="欠款金额" align="center" prop="arrearsAmount" />
            <el-table-column label="支付截止时间" align="center" prop="createdAt" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="info" @click="showUnpaidList(scope.row)">
                        查看
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 查看欠费账单弹窗 -->
        <el-dialog v-model="viewDialogVisible" title="查看欠费账单" width="600px">
            <!-- 弹窗表格：:data 已绑定 arrearsBillList（有2条数据） -->
            <el-table :data="arrearsBillList" border style="width: 100%" :show-header="true">
                <!-- 1. 序号列：用表格索引生成（不用后端字段） -->
                <el-table-column label="序号" align="center" width="80">
                    <template #default="scope">
                        <span>{{ scope.$index + 1 }}</span> <!-- 显示 1、2（对应2条数据） -->
                    </template>
                </el-table-column>

                <!-- 2. 账单编号列：null 显示“-” -->
                <el-table-column label="账单编号" align="center" width="120">
                    <template #default="scope">
                        <span>{{ scope.row.billNo || '-' }}</span> <!-- 后端 billNo 是 null，显示“-” -->
                    </template>
                </el-table-column>

                <!-- 3. 账单月份列：null 显示“-” -->
                <el-table-column label="账单月份" align="center" width="120">
                    <template #default="scope">
                        <span>{{ scope.row.billMonth || '-' }}</span> <!-- 后端 billMonth 是 null，显示“-” -->
                    </template>
                </el-table-column>

                <!-- 4. 支付截止时间列：null 显示“-”，有值则格式化 -->
                <el-table-column label="支付截止时间" align="center" width="200">
                   <template #default="scope">
                    <span>{{ parseTime(scope.row.paymentDeadline, '{y}-{m}-{d}') }}</span>
                </template>
                </el-table-column>

                <!-- 5. 应付金额列：null 显示“0.00” -->
                <el-table-column label="应付金额（元）" align="center" width="120">
                    <template #default="scope">
                        <span>{{ scope.row.payableAmount || '0.00' }}</span> <!-- 后端 payableAmount 是 null，显示“0.00” -->
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改余额查询对话框 -->

    </div>
</template>

<script setup name="Balance">
import { listBalance } from "@/api/balance/balance"
import { getBillListByElderId } from "@/api/finance/billList"

const { proxy } = getCurrentInstance()

const balanceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const viewDialogVisible = ref(false);
const arrearsBillList = ref([]);
const data = reactive({
    form: {},
    // 关键修改：将queryParams中的elderId改为elderName，与搜索表单v-model一致
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        elderName: null, // 匹配“老人姓名”搜索的v-model
        bedNo: null,
    },
    // 表单验证规则（可选，增加必填校验）
    rules: {
        elderName: [{ required: true, message: '请输入老人姓名', trigger: 'blur' }],
        bedNo: [{ required: true, message: '请输入床位号', trigger: 'blur' }],
        prepaidBalance: [{ required: true, message: '请输入预交款余额', trigger: 'blur' }],
        depositAmount: [{ required: true, message: '请输入押金金额', trigger: 'blur' }],
        updatedAt: [{ required: true, message: '请选择变动时间', trigger: 'change' }]
    }
})

const { queryParams, form, rules } = toRefs(data)
//查询欠费老人的账单
function showUnpaidList(row) {
    viewDialogVisible.value = true;
    // 获取欠费账单列表
    getBillListByElderId(row.elderId).then(response => {
        console.log("弹窗表格数据（后端返回）：", response.data);
        console.log("是否为数组：", Array.isArray(response.data)); // 必须是 true
        console.log("数据条数：", response.data.length); // 必须是 2（对应后端返回的2条数据）
        arrearsBillList.value = response.data;

    });
}
/** 查询余额查询列表 */
function getList() {
    loading.value = true
    // 此时传递给后端的参数包含elderName（老人姓名），与后端接口匹配
    listBalance(queryParams.value).then(response => {
        balanceList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}


// 表单重置
function reset() {
    form.value = {
        id: null,
        elderName: null, // 重置老人姓名
        bedNo: null,
        prepaidBalance: null,
        depositAmount: null,
        updatedAt: null,
        arrearsAmount: null,
        paymentDeadline: null,
        status: null,
        createdAt: null,
        createdBy: null,
        updatedBy: null,
        remark: null,
        extend1: null,
        extend2: null
    }
    proxy.resetForm("balanceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1 // 重置页码为1，避免搜索后跳页
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef") // 清空表单输入
    handleQuery() // 重置后重新查询（显示全部数据）
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id)
    single.value = selection.length != 1
    multiple.value = !selection.length
}



// 初始化加载列表
getList()
</script>